import 'package:enterprise_v6_app/app/components/special_operation/custom_select_time_period.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/data/entities/application/filter/filter_bean.dart';
import 'package:enterprise_v6_app/app/data/entities/application/filter/filter_entities_bean.dart';

/// description: 自定义筛选右侧弹窗 选择器
/// @Param [dataList] 选择器数据
/// @Param [onConfirm] 确认回调
/// @Param [showValue] 列表上显示的字段
/// @Param [isRadio] 是否单选
/// @Param [isShowTime] 是否展示时间选择
/// @Param [topSpacing] 顶部间距
class CustomFilterRightSheet extends StatefulWidget {
  const CustomFilterRightSheet({
    required this.dataList,
    required this.onConfirm,
    super.key,
    this.showValue = '',
    this.isRadio = false,
    this.isShowTime = false,
    this.topSpacing,
  });

  /// 选择器数据
  final List<FilterBean> dataList;

  /// 确认回调
  final Function(List<FilterBean>) onConfirm;

  ///列表上显示的字段
  final String? showValue;

  /// 是否单选
  final bool isRadio;

  /// 是否展示时间选择
  final bool isShowTime;

  /// 顶部间距
  final Widget? topSpacing;

  @override
  State<CustomFilterRightSheet> createState() => _CustomFilterRightSheetState();
}

class _CustomFilterRightSheetState extends State<CustomFilterRightSheet> {
  /// 复制的筛选列表
  List<FilterBean> _copyFilterList = [];

  /// 时间isShowTime为true时才有用
  // 开始时间
  String? startTime;

  // 结束时间
  String? endTime;

  // 时间实体
  FilterBean? itemFilterBean;

  // 时间标题
  String? timeName;

  /// 选择点击事件
  void onTap(FilterBean bean, FilterEntitiesBean item) {
    //如果是单选
    if (widget.isRadio) {
      for (var selectItem in bean.filterList) {
        //清空之前选中的数据
        selectItem.isChosen = false;
      }
      item.isChosen = true;
    } else {
      item.isChosen = !item.isChosen;
    }
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    //复制一份数据
    _copyFilterList = widget.dataList
        .map((bean) => FilterBean(
            filterList: bean.filterList
                .map((filterBean) => FilterEntitiesBean(
                      name: filterBean.name,
                      value: filterBean.value,
                      isChosen: filterBean.isChosen,
                    ))
                .toList(),
            title: bean.title,
            chosenValue: []))
        .toList();

    //如果需要展示时间
    if (widget.isShowTime) {
      for (var bean in _copyFilterList) {
        if (bean.title.contains('时间')) {
          timeName = bean.title;
          itemFilterBean = bean;
          for (var item in bean.filterList) {
            if (item.value != null) {
              switch (item.name) {
                case '开始时间':
                  startTime = item.value as String;
                  break;
                case '结束时间':
                  endTime = item.value as String;
                  break;
              }
            }
          }
        }
      }
    }
  }

  //每一项筛选所显示的内容
  Widget _getFilterView(FilterBean bean) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          bean.title,
          style: TextStyle(color: const Color(0xff333333), fontSize: 14.w, fontWeight: FontWeight.w500),
        ),
        AppGaps.vGap8,
        Wrap(
          spacing: 12.w, // 主轴(水平)方向间距
          runSpacing: 10.w, // 纵轴（垂直）方向间距
          children: bean.filterList
              .map((entitiesBean) => GestureDetector(
                  onTap: () {
                    onTap(bean, entitiesBean);
                    // if (!entitiesBean.isChosen) {
                    //   bean.chosenValue.add(entitiesBean);
                    // } else {
                    //   bean.chosenValue.remove(entitiesBean);
                    // }
                    setState(() {});
                  },
                  child: Container(
                    // margin:
                    //     EdgeInsets.symmetric(horizontal: 10.w, vertical: 6.w),
                    height: 30.w,
                    width: entitiesBean.name.length >= 6 ? null : 82.w,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(16.w)),
                      color: entitiesBean.isChosen ? const Color(0xff5C6DFF) : const Color(0xffF0F2F8),
                      border: Border.all(color: const Color(0xffF0F0F0), width: 1.w),
                    ),
                    alignment: Alignment.center,
                    child: Text(
                      entitiesBean.name,
                      style: TextStyle(
                          color: entitiesBean.isChosen ? const Color(0xffffffff) : const Color(0xff999999), fontSize: 12.w, fontWeight: FontWeight.w400),
                    ),
                  )))
              .toList(),
        ),
        AppGaps.vGap20,
      ],
    );
  }

  /// 清空
  void clearChecked() {
    for (var value in _copyFilterList) {
      if (value.filterList.isNotEmpty) {
        for (var element in value.filterList) {
          element.isChosen = false;
        }
      }
      value.chosenValue.clear();
    }
    setState(() {});
    // 如果需要展示时间
    if (widget.isShowTime) {
      startTime = '';
      endTime = '';
      for (var item in itemFilterBean!.filterList) {
        item.value = '';
      }
      confirm();
    }
  }

  /// 确认
  void confirm() {
    for (var value in _copyFilterList) {
      if (value.filterList.isNotEmpty) {
        for (var element in value.filterList) {
          if (element.isChosen) {
            value.chosenValue.add(element);
          }
        }
      }
    }
    widget.onConfirm(_copyFilterList);
    Get.back();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
            //渐变位置
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            //渐变颜色[始点颜色, 结束颜色]
            colors: [
              Color(0xffE7EAFF),
              Colors.white,
              Colors.white,
              Colors.white,
            ]),
        // borderRadius: BorderRadius.only(
        //     topLeft: Radius.circular(20.w), topRight: Radius.circular(20.w)),
        // color: Colors.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          widget.topSpacing ?? AppGaps.vGap60,
          Text(
            '   筛选',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w500,
              color: Colors.black,
            ),
          ),
          AppGaps.vGap20,
          Expanded(
              child: SingleChildScrollView(
            padding: EdgeInsets.zero,
            child: Column(
              children: [
                ..._copyFilterList.map((filterBean) {
                  if (filterBean.title.contains('时间')) {
                    return Container();
                  }
                  return Container(
                    padding: EdgeInsets.only(left: 16.w),
                    alignment: Alignment.topLeft,
                    child: _getFilterView(filterBean),
                  );
                }),
                Visibility(
                  visible: widget.isShowTime,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          timeName ?? '起止时间',
                          style: TextStyle(color: const Color(0xff333333), fontSize: 14.w, fontWeight: FontWeight.w500),
                        ),
                        AppGaps.vGap8,
                        CustomSelectTimePeriod(
                          startTime: startTime ?? '',
                          endTime: endTime ?? '',
                          needSelectAll: false,
                          onConfirm: (start, end) {
                            startTime = start;
                            endTime = end;
                            for (var bean in itemFilterBean!.filterList) {
                              switch (bean.name) {
                                case '开始时间':
                                  bean.value = startTime;
                                  break;
                                case '结束时间':
                                  bean.value = endTime;
                                  break;
                              }
                            }
                          },
                          showBorder: true,
                          iconCalendar: AppImages.icon_course_clock,
                        ),
                      ],
                    ),
                  ),
                ),
                AppGaps.vGap20,
              ],
            ),
          )),
          // Container(
          //   height: 8.w,
          //   width: AppDimens.sw,
          //   color: const Color(0xFFF2F2F2),
          // ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Container(
                  height: 40.w,
                  width: 100.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: const Color(0xffffffff),
                      border: Border.all(color: const Color(0xff5C6DFF), width: 1.w),
                      borderRadius: BorderRadius.all(Radius.circular(20.w))),
                  child: Text(
                    '重置',
                    style: TextStyle(
                      fontSize: 18.sp,
                      color: const Color(0xff5C6DFF),
                    ),
                  )).clickOnce(clearChecked),
              Container(
                  height: 40.w,
                  width: 100.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(color: const Color(0xff5C6DFF), borderRadius: BorderRadius.all(Radius.circular(20.w))),
                  child: Text(
                    '确定',
                    style: TextStyle(
                      fontSize: 18.sp,
                      color: Colors.white,
                    ),
                  )).clickOnce(confirm),
            ],
          ),
          AppGaps.vGap20,
        ],
      ),
    );
  }
}
